<template>

  <div class="app-container"  v-loading="loading">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="光纤通道" prop="fiberNum">
        <el-select v-model="queryParams.fiberNum" placeholder="请选择光纤通道" clearable @change="handleFiberChange">
          <el-option
              v-for="dict in fiberInfoList"
              :key="dict.fiberNum"
              :label="dict.fiberName"
              :value="dict"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="光纤分段" prop="warnSectionNo">
        <el-select v-model="queryParams.warnSectionNo" placeholder="请选择光纤分段" clearable @change="handleSectionInfoChange">
          <el-option
              v-for="sectionInfo in warnSectionInfoList"
              :key="sectionInfo.id"
              :label="sectionInfo.sectionName"
              :value="sectionInfo.sectionNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预警类型" prop="warnSectionNo">
        <el-select v-model="queryParams.warnNo" placeholder="请选择预警类型" clearable>
          <el-option
              v-for="warSection in warnSectionRelativeList"
              :key="warSection.id"
              :label="warSection.warnName"
              :value="warSection.warnNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检测时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeCreationTs"
            value-format="YYYY-MM-DD"
            type="daterange"
            :shortcuts="shortcuts"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
<!--        <el-button icon="Refresh" @click="dialog1Open=true">{{height}}</el-button>-->
<!--        <el-button icon="Refresh" @click="initPeakListCharts">initPeakListCharts</el-button>-->
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col  :span="20" style="padding-left: 10px">
        <el-row :gutter="20">
          <div id="peakChartDiv" style="width: 100%; height: calc(60vh - 200px);"></div>
        </el-row>
        <el-divider />
        <el-row :gutter="20">
          <div id="apiChartDiv" style="width: 100%; height: calc(60vh - 250px);"></div>
        </el-row>

      </el-col>
      <el-col  :span="4" >
        <el-table  :data="warnHisList" @selection-change="warnTableSelectChange"
                   :style="'height:' + height" highlight-current-row
                   @current-change="handleCurrentChange" @row-dblclick="handleTableDbClick">
          <el-table-column label="检测时间" align="center" prop="createTime" width="180px" />
          <el-table-column label="值" align="center" prop="values" width="190px"/>
        </el-table>
      </el-col>
    </el-row>


    <el-dialog :title="dialog1Title" v-model="dialog1Open" :close-on-press-escape="false"
               width="90%" append-to-body :fullscreen="true">
      <div id="pointChartDiv" style="width: 90%; height: calc(60vh - 150px);"></div>
    </el-dialog>


    <ul v-show="visible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li >
        <back style="width: 1em; height: 1em;" /> 关闭左侧
      </li>
      <li >
        <right style="width: 1em; height: 1em;" /> 关闭右侧
      </li>
      <li >
        <circle-close style="width: 1em; height: 1em;" /> 全部关闭
      </li>
    </ul>
  </div>
</template>

<script setup name="ZoneCharts">
import { listWarnSectionInfo } from "@/api/warn/warnSectionInfo";
import { listWarnRelative } from "@/api/warn/warnSectionRelative";
import { listFiberInfo} from "@/api/meas/fiberInfo";

import {getWarnCharts, getWarnZonePoints, getPointHis} from '@/api/warn/warnZone'
import * as echarts from "echarts";

const { proxy } = getCurrentInstance();
const { warn_his_status, line_info, fiber_info } = proxy.useDict('warn_his_status', 'line_info', 'fiber_info');

const fiberInfoList = ref([])
const warnSectionInfoList = ref([])
const warnSectionRelativeList = ref([])
const loading = ref(false);
const showSearch = ref(true);
const daterangeCreationTs = ref([]);
const warnHisList = ref([]);
const peakList = ref([]);
const nowDateStr = ref(proxy.$moment(new Date()).format('YYYY-MM-DD'))
const height= ref(document.documentElement.clientHeight - 94.5 + "px;")
const unit = ref("")
const points = ref([])
const pointHisList = ref([])

const visible = ref(false)
const top = ref(0);
const left = ref(0);
const selectedTag = ref({});
const affixTags = ref([]);
const scrollPaneRef = ref(null);

const dialog1Title = ref("点折线图")
const dialog1Open = ref(false)


// const

let peakChart = undefined
let peakChartOptions = undefined
let apiChart = undefined
// let peakChartOptions = undefined
let fiberInfo = undefined

let pointChart = undefined

const shortcuts = [
  {
    text: '近三天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
      return [start, end]
    },
  },
  {
    text: '近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
]

const queryParams = ref({
  fiberNum: null,
  warnSectionNo: null,
  warnNo: null,
})

function getList(){
}

function handleFiberChange(val){
  // console.log(val)
  fiberInfo = val
  // console.log(fiberInfo.channelModel)
  queryParams.value.fiberNum = fiberInfo.fiberNum
  getUnit()
  getWarnSectionList()
}

function handleSectionInfoChange(val){
  getWarnSectionRelativeList()
}

function doGetWarnCharts() {
  queryParams.value.params = {};
  if (null != daterangeCreationTs && '' != daterangeCreationTs) {
    queryParams.value.params["beginCreationTs"] = daterangeCreationTs.value[0];
    queryParams.value.params["endCreationTs"] = daterangeCreationTs.value[1];
  }
  // console.log(queryParams.value)
  loading.value = true;
  try {
    getWarnCharts(queryParams.value).then(resp => {
      peakList.value = resp.data.peakList
      warnHisList.value = []
      if (peakList.value && peakList.value.length > 0) {
        warnHisList.value = peakList.value.map(item => {
          return {
            createTime: item.createTime
            , values: `${item.maxValue} / ${item.minValue} / ${item.meanValue}`
            , apiId: item.apiId
            , warnNo:item.warnNo
            , fiberNum:item.fiberNum
          }
        })
      }
      initPeakListCharts()
    })
  }catch (e){
    proxy.$alert('查询异常:'+e)
  }finally {
    loading.value = false;
  }
}

function handleQuery() {
  if (!queryParams.value.fiberNum || !queryParams.value.warnSectionNo || !queryParams.value.warnNo) {
    proxy.$alert("请先选择光纤、分段以及预警段");
    return;
  }
  queryParams.value.pageNum = 1;
  doGetWarnCharts();
}
/** 重置按钮操作 */
function resetQuery() {
  daterangeCreationTs.value = [nowDateStr.value, nowDateStr.value]
  proxy.resetForm("queryRef");
  handleQuery();
}

function getFiberInfoList(){
  loading.value = true;
  listFiberInfo({}).then(response => {
    fiberInfoList.value = response.rows;
    // total.value = response.total;
    loading.value = false;
  });
}

function getWarnSectionList(){
  loading.value = true;
  listWarnSectionInfo(queryParams.value).then(response => {
    warnSectionInfoList.value = response.rows;
    // total.value = response.total;

    loading.value = false;
  });
}

function getWarnSectionRelativeList(){
  loading.value = true;
  listWarnRelative(queryParams.value).then(response => {
    warnSectionRelativeList.value = response.rows;
    // total.value = response.total;
    loading.value = false;
  });
}

function openMenu(item, e){
  console.log(item)

  console.log(e)
  const menuMinWidth = 105
  const offsetLeft = proxy.$el.getBoundingClientRect().left // container margin left
  const offsetWidth = proxy.$el.offsetWidth // container width
  const maxLeft = offsetWidth - menuMinWidth // left boundary
  const l = e.clientX - offsetLeft + 15 // 15: margin right

  if (l > maxLeft) {
    left.value = maxLeft
  } else {
    left.value = l
  }

  top.value = e.clientY
  visible.value = true
  // selectedTag.value = tag
}

function handleMenuCommand(val){
  console.log(val)
}

function handleTableDbClick(val){
  // console.log(val)
  let params = {
    apiId:val.apiId
    , warnNo: val.warnNo
    , fiberNum: val.fiberNum
  }
  doGetWarnZonePoints(params)
}

function doGetWarnZonePoints(params) {
  loading.value = true;
  try {
    getWarnZonePoints(params).then(resp => {
      points.value = []
      if (resp.data.points){
        points.value = resp.data.points
        initSimple()
      }
    })
  }catch (e) {
    proxy.$alert('查询异常:'+e)
  }finally {
    loading.value = false;
  }
}

function handleCurrentChange(v) {
  console.log(v)
  let ts = v.createTime
  let option = peakChart.getOption()
  let series = option.series
  if (series ) {
    let seriesNew = []
    let lsl = undefined
    series.forEach(item => {
      if (item.name==='max' || item.name === 'min' || item.name === 'mean') {
        seriesNew.push[item]
      } else {
        lsl = item
      }
    })
    // console.log('------------------------------ lsl -----------------------')
    // console.log(lsl)
      lsl = {
        name:"ts",
        type: "line",
        markLine: {
          symbol: "none",
          silent: true,
          data: [
            {
              xAxis: ts
            }
          ],
          lineStyle: {
            color: "#aa0000",
            width: 1,
            type: "dashed"
          }
        }
      }
    seriesNew.push(lsl)
    option.series = seriesNew
    peakChart.setOption(option)
  }
}

function init(){
  daterangeCreationTs.value = [nowDateStr.value, nowDateStr.value]
  getFiberInfoList()
}



function initSimple(){
  let tmpList = [], xData = []
  if (points && points.value  && points.value.length > 0) {
    points.value.forEach(item => {
      xData.push(item.d)
      tmpList.push(item.v)
    })
  }


  let option = {
    title: {
      // text: 'Temperature Change in the Coming Week'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {},
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      smooth: true,
      boundaryGap: false,
      data: xData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} '+unit.value
      }
    },
    dataZoom: [
      {
        type: 'slider',
        xAxisIndex: [0]
      },
      {
        type: 'inside',
        xAxisIndex: [0]
      },
      {
        type: 'slider',
        yAxisIndex:[0],
        left: '95%'
      }
    ],
    series: [
      {
        name: 'temp',
        type: 'line',
        data: tmpList,
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
      }
    ]
  };
  if (apiChart) {
    apiChart.dispose()
  }
  let apiChartDiv = document.getElementById('apiChartDiv')
  if (apiChartDiv.oncontextmenu) {
    apiChartDiv.oncontextmenu = () => {
      return false
    } //屏蔽右键默认事件
  }
  apiChart = echarts.init(apiChartDiv ,'dark');
  apiChart.setOption(option)
  //点击x轴线
  apiChart.getZr().on('dblclick', params => {
    handleApiChartDivDbClick(params)
  })

}

function handleApiChartDivDbClick(params) {
  let distance = ""
  const pointInPixel = [params.offsetX, params.offsetY]
  if (apiChart.containPixel('grid', pointInPixel)) {
    const xIndex = apiChart.convertFromPixel({ seriesIndex: 0 }, [params.offsetX, params.offsetY])[0]
    let option = apiChart.getOption()
    console.log(`xIndex:${xIndex}`)
    console.log(option.xAxis[0])
    distance = option.xAxis[0].data[xIndex]
    // apiChart.resize();
    let qp = {
      fiberNum: queryParams.value.fiberNum
      , maxDistance: distance
      , warnNo: queryParams.value.warnNo
      , params: {
        beginCreationTs: daterangeCreationTs.value[0]
        ,endCreationTs: daterangeCreationTs.value[1]
      }
    }
    loading.value = true
    try {
      getPointHis(qp).then(resp => {
        // let arr = []
        if (resp.data.list) {
          if (resp.data.list) {
            pointHisList.value = resp.data.list
            initPointChart(distance)
          }
        }
      })
    }catch (e) {

    }finally {
      loading.value = false
    }
    // console.log(`time---1----${time}`)
  }
}

function initPeakListCharts(){
  let xData = [], maxList = [], minList = [], meanList = []
  if (peakList && peakList.value && peakList.value.length > 0) {
    let item = null;
    // 按照时间 从小到大
    for (let i = peakList.value.length-1; i >=0; i--) {
      item = peakList.value[i]
      xData.push(item.createTime)
      maxList.push(item.maxValue)
      minList.push(item.minValue)
      meanList.push(item.meanValue)
    }
    /*peakList.value.forEach(item => {
      xData.push(item.createTime)
      maxList.push(item.maxValue)
      minList.push(item.minValue)
      meanList.push(item.meanValue)
    })*/
  }

  let option = {
    title: {
      // text: 'Temperature Change in the Coming Week'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {},
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      smooth: true,
      boundaryGap: false,
      data: xData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} '+unit.value
      }
    },
    dataZoom: [
      {
        type: 'slider',
        xAxisIndex: [0]
      },
      {
        type: 'inside',
        xAxisIndex: [0]
      },
      {
        type: 'slider',
        yAxisIndex:[0],
        left: '95%'
      }
    ],
    series: [
      {
        name: 'max',
        type: 'line',
        data: maxList,
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
      },
      {
        name: 'min',
        type: 'line',
        data: minList,
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
      },{
        name: 'mean',
        type: 'line',
        data: meanList,
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
      },{
        name:"ts",
        type: "line",
        markLine: {
          symbol: "none",
          silent: true,
          data: [
            {
              xAxis:"0"
            }
          ],
          lineStyle: {
            color: "#aa0000",
            width: 1,
            type: "dashed"
          }
        }
      }
    ]
  };
  // if (peakChartOptions) {
  //   console.warn("重新 绘制 echarts")
  //   document.getElementById('peakChartDiv').removeAttribute('_echarts_instance_')
  //   peakChart.clear()
  // } else {
  //   console.log("第一次 绘制 echarts")
  // }
  // peakChartOptions = option
  // if (!peakChart){
  //   initPeakChart()
  // }
  if (peakChart) {
    peakChart.dispose()
  }
  peakChart = echarts.init(document.getElementById('peakChartDiv'),'dark');
  peakChart.setOption(option)
  // peakChart.resize();
}

function getUnit(){
  if (fiberInfo && fiberInfo.channelModel) {
    if (fiberInfo.channelModel === '1') {
      unit.value = "℃"
    } else if(fiberInfo.channelModel === '2'){
      unit.value = "ue"
    } else {
      unit.value = ''
    }
  } else {
    unit.value = ''
  }

}

function initPointChart(distance){
  let tmpList = [], xData = []
  if (pointHisList && pointHisList.value  && pointHisList.value.length > 0) {
    pointHisList.value.forEach(item => {
      xData.push(item.ts)
      tmpList.push(item.v)
    })
  }
  let title = '点折线图'
  if (distance){
    title = `${distance} 米 ` + title;
  }

  let option = {
    title: {
      // text: 'Temperature Change in the Coming Week'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {},
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      smooth: true,
      boundaryGap: false,
      data: xData
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} '+unit.value
      }
    },
    dataZoom: [
      {
        type: 'slider',
        xAxisIndex: [0]
      },
      {
        type: 'inside',
        xAxisIndex: [0]
      },
      {
        type: 'slider',
        yAxisIndex:[0],
        left: '95%'
      }
    ],
    series: [
      {
        name: 'temp',
        type: 'line',
        data: tmpList,
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
      }
    ]
  };
  if (pointChart) {
    pointChart.dispose()
  }

  loading.value = false
  dialog1Title.value = title
  dialog1Open.value = true

  // 新建一个promise对象
  let newPromise = new Promise((resolve) => {
    resolve()
  })
  //然后异步执行echarts的初始化函数
  newPromise.then(() => {
    //	此dom为echarts图标展示dom
    let pointChartDiv = document.getElementById('pointChartDiv')
    /*if (pointChartDiv.oncontextmenu) {
      pointChartDiv.oncontextmenu = () => {
        return false
      } //屏蔽右键默认事件
    }*/
    pointChart = echarts.init(pointChartDiv ,'dark');
    pointChart.setOption(option)
  })
}

function warnTableSelectChange(selection){

}
function initPeakChart(){
  if (!peakChart) {
    peakChart = echarts.init(document.getElementById('peakChartDiv'),'dark');
  }
}

function initApiChart(){
  if (!apiChart) {
    apiChart = echarts.init(document.getElementById('apiChartDiv'),'dark');
  }
}
nextTick(() => {

  console.log(222)
  // initPeakChart()
  // initApiChart()

  window.addEventListener("resize", function(){
    peakChart.resize();
  });
});
onMounted(()=>{
  console.log(111)
  // initData()
  // peakChart = echarts.init(document.getElementById('peakChartDiv'));

  // console.log(`初始化 peakChart--`, peakChart)

})
init()

</script>

<style scoped lang="scss">

/*#peakChartDiv {
  position: absolute;
  width: 80%;
  height: calc(60vh - 184px); !* 高度减去 面包屑-撑满 *!
}
#apiChartDiv {
  //position: absolute;
  padding-top: 500px;
  width: 80%;
  height: calc(60vh - 184px); !* 高度减去 面包屑-撑满 *!
}*/
</style>
